<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>完善拖拽</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            cursor: move;
        }
    </style>
</head>
<body>
    <div class="box"></div>

    <script>

        /* 
            完善部分【已修改】： 
                * 光标在盒子正中间
                * 只能在可视窗口移动

        */

        var box = document.querySelector('.box');

        box.onmousedown = function(e){
            
            // 获取光标在box上的水平、垂直距离：居中定死
            var boxLeft = box.offsetWidth/2;
            var boxTop = box.offsetHeight/2;

            // 移动
            document.onmousemove = function(eve){
                // 盒子的左边距和上边距
                var oX = eve.clientX- boxLeft;
                var oY = eve.clientY - boxTop;

                // 左边距不超过(window的可视区域宽度-整个box的宽度)
                if(oX>window.innerWidth-box.offsetWidth){
                    oX=window.innerWidth-box.offsetWidth;
                }else if(oX<0){
                    oX = 0;
                }

                // 上边距不超过(html的可视区域高度-整个box的高度)
                if(oY>document.documentElement.clientHeight-box.offsetHeight){
                    oY=document.documentElement.clientHeight-box.offsetHeight;
                }else if(oY<0){
                    oY = 0;
                }

                // 定位
                box.style.left = oX +'px';
                box.style.top = oY +'px';
            };
        }

        // 鼠标抬起时，停止移动
        document.onmouseup = function(){
			document.onmousemove = null;
		}
    </script>
</body>
</html>